package cn.lynu.javaweb.api;

import com.alibaba.fastjson2.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

class User{
    public String name;
    public String pass;
    public User(String un, String pw){
        this.name = un;
        this.pass = pw;
    }
}

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(
        HttpServletRequest req,
        HttpServletResponse resp
    ) throws ServletException, IOException {
        // 设置请求、响应及响应头的字符编码
        req.setCharacterEncoding("utf8");
        resp.setCharacterEncoding("utf8");
        resp.setContentType("application/json;charset=utf-8");


        PrintWriter out = resp.getWriter();

        // 获取reader对象，读取请求体
        BufferedReader reader = req.getReader();

        StringBuilder sb = new StringBuilder();
        String line;
        // 以字符串形式逐行读取请求体内容
        while((line=reader.readLine())!=null){
            sb.append(line);
        }
        //out.println(sb.toString());

        User user = JSON.parseObject(sb.toString(), User.class);

        if(user.name.equals("admin") && user.pass.equals("123456")){
            req.getSession().setAttribute("username","张三");

            out.println("{\"code\":200,\"msg\":\"登录成功\"}");
        }else{
            out.println("{\"code\":500,\"msg\":\"登录失败\"}");
        }



    }
}
